import React, { useEffect, useRef, useState } from 'react'
import { Button, Card, Divider, Form, Input, message, Popconfirm, Select, Space, Table } from 'antd'
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import { useSetState, useAntdTable } from 'ahooks'
import TableToolBar from '@/components/TableToolBar'
import { PageConfig } from '@/config'
import View from '@/components/View'
import { getUserList } from '@/data'
import { debounce } from 'lodash'
import Transition from '@/components/Transition'
import Edit from './edit'

const { Option } = Select

interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}
export type ColType=ColumnsType<DataType>[number] & {selected?:boolean, dataIndex:string}
const StandarTable = () => {
  const [state, setState] = useSetState({ showSearch: false })
  const [isOpenEdit, setIsOpenEdit] = useState(false)
  const [userData, setUserData] = useState()
  const [form] = Form.useForm()
  const nodeRef = useRef(null)

  useEffect(() => {
    setState({ showSearch: true })
    changeColumn()
  }, [])

  const { tableProps, search, run: getTableData } = useAntdTable(getUserList, {
    defaultPageSize: 10,
    form,
  })
  const { submit } = search

  Object.assign(tableProps.pagination, PageConfig.options)

  // 刷新数据
  const refreshData = debounce((filter = form.getFieldsValue()) => {
    getTableData(PageConfig.base, filter)
  }, 500)

  // 重置
  const reset = () => {
    form.resetFields()
    refreshData()
  }

  // 搜索，500ms内连续点击只响应最后一次请求
  const onSearch = debounce(() => {
    search.submit()
  }, 500)

  // 切换搜索隐藏
  const onToggleSearch = () => {
    setState({ showSearch: !state.showSearch })
  }
  const [columns, setColumns] = useState<ColType[]>([
    {
      title: '姓名',
      dataIndex: 'name.last',
      render: (text: any, record: any) => {
        return (<span>我叫 {record.name.last} </span>)
      },
    },
    {
      title: '邮箱',
      selected: false,
      dataIndex: 'email',
    },
    {
      title: '电话',
      dataIndex: 'phone',
    },
    {
      title: '性别',
      dataIndex: 'gender',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 100,
      render: (value: string, row: object) => (
        <Space>
          <Button type="link" onClick={() => { onEdit(row) }}>
            <Space><EditOutlined />修改</Space>
          </Button>
          <Popconfirm title="确定要删除吗?" onConfirm={() => { onDelete(row) }}>
            <Button type="link" danger>
              <Space><DeleteOutlined />删除</Space>
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ])
  const changeColumn = (dataIndex?:string) => {
    columns.forEach((item) => {
      if (item.dataIndex === dataIndex) {
        item.selected = !item.selected
      }
    })
    setColumns([...columns])
  }
  const tip = () => {
    setIsOpenEdit(true)
  }

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const onSelectChange = (keys: React.Key[]) => {
    setSelectedRowKeys(keys)
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  }
  const hasSelected = !selectedRowKeys.length

  // 批量删除
  const onBetchDelete = debounce(() => {
    if (!selectedRowKeys.length) {
      message.error('至少选择一个')
      return
    }

    setTimeout(() => {
      message.success('删除成功')
      search.submit()
    }, 200)
  }, 500)

  const onAdd = () => {
    tip()
  }

  const onEdit = (row: any) => {
    setUserData(row)
    setIsOpenEdit(true)
  }
  const onDelete = (row: any) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const data = { name: 'jikey', ...row }
        resolve(data)
      }, 200)
    }).then(() => {
      message.success('删除成功')
      search.submit()
    })
  }

  // 编辑回调
  const onOkEditUser = () => {
    search.submit()
  }

  // 搜索模块
  const searchNode = (
    <div className="app-query-header" ref={nodeRef}>
      <div className="app-card-header flex justify-between">
        <div className="filter">
          <Form
            name="basic"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            initialValues={{ remember: true }}
            form={form}
          >
            <Form.Item
              label="用户名称"
              className="app-card-header-form query"
            >
              <Form.Item
                name="name"
                rules={[{ message: '请输入用户名称' }]}
              >
                <Input onPressEnter={onSearch} autoComplete="off" />
              </Form.Item>
              <Form.Item
                label="手机号码"
                name="phone"
                rules={[{ message: '请输入手机号码' }]}
              >
                <Input onPressEnter={() => search.submit()} autoComplete="off" />
              </Form.Item>
              <Form.Item
                label="状态"
                name="status"
                rules={[{ message: '请选择状态' }]}
              >
                <Select style={{ width: '150px' }}>
                  <Option value="1">正常</Option>
                  <Option value="2">停用</Option>
                </Select>
              </Form.Item>
              <Space>
                <Button type="primary" onClick={submit}>查询</Button>
                <Button onClick={reset}>重置</Button>
              </Space>
            </Form.Item>
            <Form.Item label="筛选">
              <Space align="start">
                <Form.Item name="grade_code">
                  <Select style={{ width: '150px' }}>
                    <Option value="jack">Jack</Option>
                    <Option value="lucy">Lucy</Option>
                    <Option value="tom">Tom</Option>
                  </Select>
                </Form.Item>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </div>
      <Divider />
    </div>
  )

  return (
    <View className="app-standard-table">
      <Card title="标准表格">
        <Transition active={state.showSearch}>
          {state.showSearch && searchNode}
        </Transition>
        <div className="app-table-action">
          <div className="app-table-btn">
            <Space size={15}>
              <Button type="primary" onClick={() => { onAdd() }} icon={<PlusOutlined />}>新增</Button>
              <Button disabled={hasSelected} onClick={() => { onBetchDelete() }} icon={<DeleteOutlined />}>删除</Button>
            </Space>
          </div>
          <div className="app-table-action-right">
            <TableToolBar toggleSearch={onToggleSearch} refreshData={refreshData} columnData={columns} changeColumn={changeColumn} />
          </div>
        </div>

        <Table
          bordered
          rowKey="cell"
          size="middle"
          rowSelection={rowSelection}
          columns={columns.filter((item) => item.selected !== false)}
          {...tableProps}
        />
      </Card>
      {/* <Edit data={userData} isOpenEdit={isOpenEdit} setIsOpenEdit={setIsOpenEdit} onOkAction={onOkEditUser} /> */}
    </View>
  )
}

export default StandarTable
